package com.example.lzbase;

import android.location.LocationListener;
import android.widget.Toast;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import pub.devrel.easypermissions.EasyPermissions;

public class BasePermissionsFragment extends Fragment implements EasyPermissions.PermissionCallbacks{
    private LocationPermissionListener locationPermissionListener;

    /**
     *  @param permissions 权限
     * @param rationale   说明
     * @param requestCode  requestCode
     */
    public  void requestPersion(@NonNull String permissions, String rationale, int requestCode){

        EasyPermissions.requestPermissions(this,rationale,requestCode, permissions);

    }
    public  void requestPersion(@NonNull String[] permissions, String rationale, int requestCode){

        EasyPermissions.requestPermissions(this,rationale,requestCode, permissions);

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if(requestCode==100){
            startLocation();

        }


    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
            if(requestCode==100)
            Toast.makeText(getContext(),R.string.access_location_null,Toast.LENGTH_SHORT).show();
    }

    public  boolean  hasPermission(String permission){

        return  EasyPermissions.hasPermissions(getContext(),permission);
    }
    public  boolean  hasPermission(String[] permission){

        return  EasyPermissions.hasPermissions(getContext(),permission);
    }

    public void checkLocation(LocationPermissionListener locationPermissionListener){
        this.locationPermissionListener=locationPermissionListener;
        if(hasPermission(new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION,
        } )){

            startLocation();
        }else
        {
            requestPersion(new String[]{
                    android.Manifest.permission.ACCESS_COARSE_LOCATION,
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
            },getString(R.string.access_location),100);
        }
    }

    private void  startLocation(){
            if(this.locationPermissionListener!=null){
                this.locationPermissionListener.hasLocationPermission();
            }
    }

    public  interface LocationPermissionListener{
        public  void  hasLocationPermission();
    }

}
